package com.avic.rong.questionOrAnswer.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.fragment.FragmentWenDa;
import com.avic.rong.questionOrAnswer.adapter.QuestionListAdapter;
import com.avic.rong.questionOrAnswer.api.AddQuestionsApi;
import com.avic.rong.questionOrAnswer.api.AssociateApi;
import com.avic.rong.questionOrAnswer.api.UpdateQuestionApi;
import com.avic.rong.questionOrAnswer.bean.AssociateBean;
import com.avic.rong.questionOrAnswer.bean.UpdataDataQuestionBean;
import com.avic.rong.questionOrAnswer.imgSelect.FullyGridLayoutManager;
import com.avic.rong.questionOrAnswer.imgSelect.GridImageAdapterByDust;
import com.avic.rong.richEditor.keyboard.KeyboardUtils;
import com.avic.rong.userOrder.api.UploadApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.io.File;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class QuestionActivity extends BaseActivity {



    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rec_up_img)
    RecyclerView rcUploadImg;
    @BindView(R.id.question_list)
    RecyclerView questionList;
    @BindView(R.id.et_question)
    EditText etQuestion;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tv_add_message)
    TextView tvAddMessage;
    @BindView(R.id.ll_search)
    RelativeLayout llSearch;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.iv_clear)
    ImageView iv_clear;
    @BindView(R.id.iv_question)
    ImageView iv_question;


    private GridImageAdapterByDust adapter;
    /**
     * 选择的本地图片列表
     */
    private List<LocalMedia> selectList = new ArrayList<>();

    /**
     * 图片上传成功后
     */
    private List<String> imageBeans = new ArrayList<>();
    private QuestionListAdapter questionListAdapter;
    private List<AssociateBean> listDataLX = new ArrayList<>();

    public static String UPDATA_QUESTION="updata_question";
    private UpdataDataQuestionBean updataDataQuestionBean;
    public static String searchTerm="";

    public static int QUESTION_SHOW=200;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_question;
    }

    @Override
    protected void initView() {
        llSearch.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);
        updataDataQuestionBean = (UpdataDataQuestionBean) getIntent().getSerializableExtra(UPDATA_QUESTION);
        loading_layout.setStatus(LoadingLayout.SUCCESS);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
        rcUploadImg.setLayoutManager(manager);

        adapter = new GridImageAdapterByDust(context, mOnAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(3);
        rcUploadImg.setAdapter(adapter);

        questionList.setLayoutManager(new LinearLayoutManager(this));
        questionListAdapter = new QuestionListAdapter(this, listDataLX);
        questionList.setAdapter(questionListAdapter);
        if (updataDataQuestionBean!=null){
            if (updataDataQuestionBean.getTitle().contains("<br>")||updataDataQuestionBean.getDesc().contains("<br>")){
                String title = updataDataQuestionBean.getTitle().replaceAll("<br>", "\n");
                String desc = updataDataQuestionBean.getDesc().replaceAll("<br>", "\n");
                etQuestion.setText(title);
                etContent.setText(desc);
            }else {
                etQuestion.setText(updataDataQuestionBean.getTitle());
                etContent.setText(updataDataQuestionBean.getDesc());
            }

            if (!TextUtils.isEmpty(updataDataQuestionBean.getImgs())){
                List<String> imgs = Arrays.asList(updataDataQuestionBean.getImgs().split(";"));

                selectList.clear();
                for (int i = 0; i < imgs.size(); i++) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setCutPath(imgs.get(i));
                    localMedia.setCompressPath(imgs.get(i));
                    localMedia.setPath(imgs.get(i));
                    selectList.add(localMedia);
                }

                adapter.setList(selectList);
                adapter.notifyDataSetChanged();

            }
        }



        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(context);
                } else {
                    Toast.makeText(context, "读取内存卡权限被拒绝", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });


    }

    @Override
    protected void addListener() {
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                EditUtils.showORhideSoftKeyboard(QuestionActivity.this);
                KeyboardUtils.hideSoftInput(QuestionActivity.this);
                finish();
            }
        });
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String qestion = etQuestion.getText().toString();
                String qestionContent = etContent.getText().toString();
                if (TextUtils.isEmpty(qestion)){
                    ToastTools.showToast(QuestionActivity.this,"请填写问题");
                    return;
                }

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                //每次上传都清空成功的集合
                imageBeans.clear();
                if (selectList!=null&&selectList.size()>0){
                    for (LocalMedia localMedia : selectList) {
                        String compressPath = localMedia.getCompressPath();
                        if(!compressPath.contains("http")){
                            File file = new File(compressPath);
                            doUpload(file);
                        }else {
                            imageBeans.add(compressPath);
                            /**  标识  全部上传成功  **/
                            if (selectList.size() == imageBeans.size()) {


                                StringBuffer sb = new StringBuffer();

                                for (int i = 0; i < imageBeans.size(); i++) {
//                        String id = imageBeans.get(i).getId();
                                    String s = imageBeans.get(i);
                                    if (i == imageBeans.size() - 1) {
                                        sb.append(s);

                                    } else {
                                        sb.append(s);
                                        sb.append(";");
                                    }

                                }
                                if (updataDataQuestionBean!=null){
                                    updataQuestion(sb.toString(),updataDataQuestionBean.getQueId()+"");
                                }else {
                                    questionQes(sb.toString());
                                }
                            }
                        }

     /*       FileInputStream fileInputStream = new FileInputStream(pdfFile);
            MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

*/
                    }
                }else {
                    if (updataDataQuestionBean!=null){
                        updataQuestion("",updataDataQuestionBean.getQueId()+"");
                    }else {
                        questionQes("");
                    }

                }

            }


        });
        etQuestion.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {



            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()!=0){
                    associate(s.toString());
                    searchTerm=s.toString();
                }

                if (s.length()!=0){
                    iv_question.setVisibility(View.GONE);
                    iv_clear.setVisibility(View.VISIBLE);

                    llSearch.setVisibility(View.VISIBLE);
                    llContent.setVisibility(View.GONE);
                }else {
                    iv_question.setVisibility(View.VISIBLE);
                    iv_clear.setVisibility(View.GONE);

                    llSearch.setVisibility(View.GONE);
                    llContent.setVisibility(View.VISIBLE);
                }
            }
        });
        tvAddMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llSearch.setVisibility(View.GONE);
                llContent.setVisibility(View.VISIBLE);
            }
        });
        iv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etQuestion.setText("");
            }
        });

        questionList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                hideSoftKeyboard(QuestionActivity.this);
            }
        });

        iv_question.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QuestionActivity.this, QuestionExplainActivity.class);
                startActivity(intent);
            }
        });

        etQuestion.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return(event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

    }

    private void updataQuestion(String imgs,String queID) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            String qestion = etQuestion.getText().toString();
            String qestionContent = etContent.getText().toString();
            if (qestion.contains("\n")||qestionContent.contains("\n")){
                qestion.replaceAll("\n","<br>");
                qestionContent.replaceAll("\n","<br>");
            }

            Map<String, String> map = new HashMap<>();
            map.put("token",getSharedPreferencesUtil().getLogintoken());
            map.put("title",qestion);
            map.put("desc",qestionContent);
            map.put("imgs",imgs);
            map.put("queId",queID);

            UpdateQuestionApi updateQuestionApi = new UpdateQuestionApi(QuestionActivity.this, simpleOnNextListenerQestion);
            updateQuestionApi.setCache(false);
            updateQuestionApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(updateQuestionApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(updateQuestionApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    private void associate(String content) {
        if (!content.isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("title", content);
            final AssociateApi associateApi = new AssociateApi(this, simpleOnNextListener);
            associateApi.setCache(false);
            associateApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(associateApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(associateApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    /**
     * 新增接口回调
     */
    GridImageAdapterByDust.onAddPicClickListener mOnAddPicClickListener = new GridImageAdapterByDust.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {


            PictureSelector.create((Activity) context)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(3)
                    .maxSelectNum(3 - selectList.size())


                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(3)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

        }
    };

    /**
     * 选择后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> tempList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    if (tempList != null) {

                        selectList.addAll(tempList);
                    }

                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();

                    break;
            }
        }
    }

    /**
     * 上传
     *
     * @param files
     */
    private void doUpload(File files) {


        if (files != null) {
            UploadApi uploadApi = new UploadApi(this, simpleOnNextListenerSCPic);

            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), files);

            MultipartBody.Part part = MultipartBody.Part.createFormData("file", files.getName(), requestBody);
            uploadApi.setPart(part);
            HttpManager.getInstance().doHttpDeal(uploadApi);

        }

    }

    //上传图像
    HttpOnNextListener simpleOnNextListenerSCPic = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(QuestionActivity.this, subjects.getMsg());
                return;
            }
            String pic = (String) subjects.getData();
            if (!TextUtils.isEmpty(pic)) {

                imageBeans.add(pic);

                /**  标识  全部上传成功  **/
                if (selectList.size() == imageBeans.size()) {

                    ToastTools.showToast(context, "图片全部上传成功！");


                    StringBuffer sb = new StringBuffer();

                    for (int i = 0; i < imageBeans.size(); i++) {
//                        String id = imageBeans.get(i).getId();
                        String s = imageBeans.get(i);
                        if (i == imageBeans.size() - 1) {
                            sb.append(s);

                        } else {
                            sb.append(s);
                            sb.append(";");
                        }

                    }
                    if (updataDataQuestionBean!=null){
                        updataQuestion(sb.toString(),updataDataQuestionBean.getQueId()+"");
                    }else {
                        questionQes(sb.toString());
                    }
                }

            }


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void questionQes(String imgs) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            String qestion = etQuestion.getText().toString();
            String qestionContent = etContent.getText().toString();
            if (qestion.contains("\n")||qestionContent.contains("\n")){
                qestion = qestion.replaceAll("\n", "<br>");
                qestionContent = qestionContent.replaceAll("\n", "<br>");
            }
            Map<String, String> map = new HashMap<>();
            map.put("token",getSharedPreferencesUtil().getLogintoken());
            map.put("title",qestion);
            map.put("desc",qestionContent);
            map.put("imgs",imgs);

            final AddQuestionsApi addQuestionsApi = new AddQuestionsApi(QuestionActivity.this, simpleOnNextListenerQestion);
            addQuestionsApi.setCache(false);
            addQuestionsApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(addQuestionsApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(addQuestionsApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            listDataLX.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(QuestionActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            List<AssociateBean> data = (List<AssociateBean>) subjects.getData();
            listDataLX.addAll(data);
            questionListAdapter.notifyDataSetChanged();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };
    HttpOnNextListener simpleOnNextListenerQestion = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(QuestionActivity.this, subjects.getMsg());
                if (subjects.getCode().equals("500")){
                    loading_layout.setStatus(LoadingLayout.SUCCESS);
                }
                FragmentWenDa.setIs_Resum(false);
                return;
            }
            FragmentWenDa.setIs_Resum(true);
            Intent intent = new Intent();
            setResult( RESULT_OK,intent);
            loading_layout.setStatus(LoadingLayout.SUCCESS);

            finish();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };
    public static Intent queryIntent(Context context, UpdataDataQuestionBean updataDataQuestionBean) {
        Intent intent = new Intent(context, QuestionActivity.class);
        intent.putExtra(UPDATA_QUESTION, updataDataQuestionBean);
        return intent;
    }

    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


}
